import {PlainBindingNamespace} from "../../../packages";
import {deepcopy} from "@peryl/utils/deepcopy";
import {http} from "../plain-design/http";

export const QueryBindingVariableData = async (queryEntity: PlainBindingNamespace.iBindingQueryEntity<any>):
  Promise<PlainBindingNamespace.iBindingQueryEntity<any>> => {
  const respQueryEntity = deepcopy(queryEntity);

  const query = (!queryEntity.query ? undefined : (typeof queryEntity.query === "string" ? JSON.parse(queryEntity.query) : queryEntity.query)) || {};
  const body = (!queryEntity.body ? undefined : (typeof queryEntity.body === "string" ? JSON.parse(queryEntity.body) : queryEntity.body)) || {};
  const headers = (!queryEntity.headers ? undefined : (typeof queryEntity.headers === "string" ? JSON.parse(queryEntity.headers) : queryEntity.headers)) || {};

  if (!queryEntity.disablePaginationParameter) {
    const assignTarget = queryEntity.method.toLowerCase() === 'get' ? query : body;
    Object.entries({
      page: queryEntity.page,
      size: queryEntity.pageSize,
      all: queryEntity.queryAllData
    }).forEach(([key, val]) => {
      if (assignTarget[key] == null) {
        assignTarget[key] = val;
      }
    });
  }

  const resp = await http.request<
    { code: number, fail: boolean, message?: string } &
    ({ list: any[], hasNext: boolean } | { result: any })
  >({
    url: queryEntity.url,
    method: queryEntity.method,
    params: query,
    data: body,
    headers: headers,
  });
  if (!!resp.message) {
    respQueryEntity.errorMessage = resp.message;
    respQueryEntity.errorCode = resp.code;
    respQueryEntity.errorData = (resp as any).result;
  } else {
    if ('list' in resp) {
      respQueryEntity.data = resp.list;
      respQueryEntity.loaded = !resp.hasNext;
    } else {
      respQueryEntity.data = resp.result;
    }
  }
  return respQueryEntity;
};
